package com.zoffy.codesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.zoffy.codesandbox.model.ExecuteCodeRequest;
import com.zoffy.codesandbox.model.ExecuteCodeResponse;
import com.zoffy.codesandbox.model.ExecuteMessage;
import com.zoffy.codesandbox.model.JudgeInfo;
import com.zoffy.codesandbox.utils.ProcessUtil;
import io.micrometer.common.util.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
public class JavaCodeSandbox implements CodeSandbox {
    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    private static final long TIME_OUT = 5000L;


    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();

        //运行
        try {
            //保存代码
            File codeFile = saveCode2File(code);
            //编译代码
            compileCode(codeFile);
            //获取代码结果
            List<ExecuteMessage> executeMessageList = runCodeFile(codeFile, inputList);
            ExecuteCodeResponse outputResponse = getOutputResponse(executeMessageList);
            deleteFile(codeFile);
            return outputResponse;
        } catch (Exception e) {
            return getErrorResponse(e);
        }
    }

    private File saveCode2File(String code) {
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        // 判断全局代码目录是否存在，没有则新建
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }

        // 把用户的代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        return FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

    }

    private ExecuteMessage compileCode(File codeFile) {
        String s = "javac -encoding utf8 ";
        try {
            Process process = Runtime.getRuntime().exec(s + codeFile.getPath());
            ExecuteMessage executeMessage = ProcessUtil.runProcessAndGetMessage(process);
            if (executeMessage.getExitCode() != 0) {
                throw new RuntimeException("编译错误");
            }
            return executeMessage;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public List<ExecuteMessage> runCodeFile(File file, List<String> inputList) {
        String parentPath = file.getParentFile().getAbsolutePath();
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String input : inputList) {
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s -Djava.security.policy= Main %s", parentPath, input);
            try {
                Process process = Runtime.getRuntime().exec(runCmd);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(TIME_OUT);
                            System.out.println("超时终止程序");
                            process.destroy();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }

                    }
                }).start();
                ExecuteMessage executeMessage = ProcessUtil.runProcessAndGetMessage(process);
                executeMessageList.add(executeMessage);
            } catch (Exception e) {
                System.out.println("执行错误");
            }
        }
        return executeMessageList;
    }

    public ExecuteCodeResponse getOutputResponse(List<ExecuteMessage> executeMessageList) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        long maxTime = 0;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StringUtils.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            long time = executeMessage.getTime();
            maxTime = Math.max(time, maxTime);
        }
        if (outputList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        executeCodeResponse.setJudgeInfo(judgeInfo);
        return executeCodeResponse;
    }

    public boolean deleteFile(File file) {
        File parentFile = file.getParentFile();
        if (parentFile != null) {
            return FileUtil.del(parentFile);
        }
        return true;
    }

    private ExecuteCodeResponse getErrorResponse(Exception e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }
}
